<?php
/**
 * Created by PhpStorm.
 * User: wxy
 * Date: 2018/11/7
 * Time: 16:40
 */

namespace frontend\modules\common\models\dataTemplate;


use PHPExcel;

class DownloadTemp
{
    protected $TempData;

    /**
     * DownloadTemp constructor.
     * @param BaseTemp $TempData
     */
    public function __construct(BaseTemp $TempData)
    {
        $this->TempData = $TempData;
    }

    /**
     * @return bool
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Writer_Exception
     */
    public function down()
    {

        $header = $this->getHeader();
        $data = $this->getBody();
        $filename = $this->getName();

        if (!is_array($data) || !is_array($header)) return false;
        $objPHPExcel = new PHPExcel();
        $objPHPExcel->getProperties()->setCreator("Maarten Balliauw");
        $objPHPExcel->getProperties()->setLastModifiedBy("Maarten Balliauw");
        $objPHPExcel->getProperties()->setTitle("Office 2007 XLSX Test Document");
        $objPHPExcel->getProperties()->setSubject("Office 2007 XLSX Test Document");
        $objPHPExcel->getProperties()->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.");
        $objPHPExcel->setActiveSheetIndex(0);
        //添加头部
        $hk = 0;
        foreach ($header as $k => $v) {
            $colum = \PHPExcel_Cell::stringFromColumnIndex($hk);
            $objPHPExcel->getActiveSheet()->setCellValue($colum . "1", $v);
            $hk += 1;
        }
        $column = 2;
        $objActSheet = $objPHPExcel->getActiveSheet();
        foreach ($data as $key => $rows) {
            //行写入
            $span = 0;
            foreach ($rows as $keyName => $value) {
                // 列写入
                $j = \PHPExcel_Cell::stringFromColumnIndex($span);
                $objActSheet->setCellValue($j . $column, $value);
                $span++;
            }
            $column++;
        }
        $objPHPExcel->getActiveSheet()->setTitle($filename);
        $objWriter = new \PHPExcel_Writer_Excel2007($objPHPExcel);
        header("Pragma:public");
        header("Content-Type:application/x-msexecl;name=\"{$filename}.xlsx\"");
        header("Content-Disposition:inline;filename=\"{$filename}.xlsx\"");
        $objWriter->save("php://output");
    }

    /**
     * @return mixed
     */
    private function getHeader()
    {
        return $this->TempData->header;
    }

    /**
     * @return mixed
     */
    private function getBody()
    {
        return $this->TempData->body;
    }

    /**
     * @return mixed
     */
    private function getName()
    {
        return $this->TempData->filename;
    }

}